package com.sunyur.tailor.channel.service.inner.purchase.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import com.sunyur.tailor.channel.common.inner.base.SunyurListResult;
import com.sunyur.tailor.channel.common.inner.base.SunyurResult;
import com.sunyur.tailor.channel.common.inner.util.SunyurClientUtil;
import com.sunyur.tailor.channel.common.inner.util.SunyurResultUtil;
import com.sunyur.tailor.channel.common.middle.base.ChannelListResult;
import com.sunyur.tailor.channel.common.middle.base.ChannelResult;
import com.sunyur.tailor.channel.common.middle.enums.MiddleResultEnum;
import com.sunyur.tailor.channel.common.middle.util.ChannelListResultUtil;
import com.sunyur.tailor.channel.common.middle.util.ChannelResultUtil;
import com.sunyur.tailor.channel.common.middle.util.RestTemplateUtil;
import com.sunyur.tailor.channel.service.inner.purchase.model.*;
import com.sunyur.tailor.channel.service.inner.purchase.param.*;
import com.sunyur.tailor.channel.service.inner.purchase.service.SunyurPurchaseApplyService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @Author 99288
 * @Description 请购实现
 * @Param
 * @return
**/
@Service("purchaseApplyService")
public class SunyurPurchaseApplyServiceImpl implements SunyurPurchaseApplyService {

    private static final Logger LOGGER_INFO = LoggerFactory.getLogger(SunyurPurchaseApplyServiceImpl.class);
    private static final Logger LOGGER_ERROR = LoggerFactory.getLogger(SunyurPurchaseApplyServiceImpl.class);

    /**
     * 请求商越Client
     */
    @Autowired
    private SunyurClientUtil sunyurClient;

    /**
     * 获取采购单头信息 链接
     */
    @Value("${sunyur.api.getApplyHeadByCode}")
    private String getApplyHeadByCode;

    /**
     * 批量获取采购单行信息 链接
     */
    @Value("${sunyur.api.getApplyItemsByCodes}")
    private String getApplyItemsByCodes;

    /**
     * 获取单个采购单行信息 链接
     */
    @Value("${sunyur.api.getApplyItemsByCode}")
    private String getApplyItemsByCode;

    @Value("${sunyur.api.getListPriceParity}")
    private String getListPriceParity;

    @Autowired
    RestTemplateUtil restTemplateUtil;
    
    @Value("${sunyur.api.findSourceDetail}")
    private String findSourceDetail;

    @Value("${sunyur.api.getStrategyOrderList}")
    private String getStrategyOrderList;

    @Value("${sunyur.domain}")
    private String domain;




    @Override
    public ChannelResult<StrategyOrderListModel> getStrategyOrderList(StrategyOrderListParam strategyOrderListParam) {
//        String body = HttpRequest.post(domain + findSourceDetail).body(JSON.toJSONString(strategyOrderListParam)).execute().body();
//        LOGGER_INFO.info("请求商越接口，请求参数：{}，接口地址：{}, 返回结果：{}", JSON.toJSONString(strategyOrderListParam),domain+getStrategyOrderList, body);

        SunyurResult sunyurResult = sunyurClient.execPost(findSourceDetail, JSON.toJSONString(strategyOrderListParam), new TypeReference<SunyurResult<SunyurListResult<StrategyOrderListModel>>>() {
        });
        LOGGER_INFO.info("请求商越接口，请求参数：{}，接口地址：{}, 返回结果：{}", JSON.toJSONString(strategyOrderListParam),findSourceDetail, JSON.toJSONString(sunyurResult));
        return null;
    }

    @Override
    public ChannelResult<StrategyOrderDetailModel> getStrategyOrderDetail(StrategyOrderDetailParam strategyOrderDetailParam) {
        SunyurResult sunyurResult = sunyurClient.execPost(findSourceDetail, JSON.toJSONString(strategyOrderDetailParam),null);

        if (!SunyurResultUtil.isSuccess(sunyurResult)) {
            LOGGER_ERROR.error("getStrategyOrderDetail call sunyur request fail, param is {}, result is {}", JSON.toJSONString(strategyOrderDetailParam), JSON.toJSONString(sunyurResult));
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), JSON.toJSONString(sunyurResult.getErrorMessage()));
        }
        return ChannelResultUtil.success(JSON.parseObject(JSON.toJSONString(sunyurResult.getContent()), StrategyOrderDetailModel.class));
    }

    public SunyurResult<Boolean> deliverPurchaseTeam(String param) throws Exception {
        LOGGER_INFO.info("PurchaseApplyServiceImpl deliverPurchaseTeam param:{}", param);
        SunyurResult<Boolean> result = new SunyurResult<>();
        if(StringUtils.isBlank(param)){
            result.setErrorMessage(MiddleResultEnum.PARAM_NULL.getCode(), MiddleResultEnum.PARAM_NULL.getValue());
        }else{

        }
        LOGGER_INFO.info("PurchaseApplyServiceImpl deliverPurchaseTeam return:{}", JSON.toJSONString(result));
        return result;
    }

    /**
     * @description 根据请购行号 查询 采购单行集合
     * @param purchaseApplyItemsByCodesParam
     * @return com.sunyur.tailor.channel.common.middle.base.ChannelResult<java.util.List<com.sunyur.tailor.channel.service.inner.purchase.vo.PurchaserApplyItemVO>>
     * @author yu.chen
     * @date 2021/4/23 21:40
     * @Version v1.0
     */
    @Override
    public ChannelListResult<PurchaserApplyItemModel> getPurchaserApplyItemsByItemCodes(PurchaseApplyItemsByCodesParam purchaseApplyItemsByCodesParam) throws Exception {
        LOGGER_INFO.info("SunyurPurchaseApplyServiceImpl getPurchaserApplyItemsByItemCodes param is {}", JSON.toJSONString(purchaseApplyItemsByCodesParam));
        if (ObjectUtils.isEmpty(purchaseApplyItemsByCodesParam) || CollectionUtils.isEmpty(purchaseApplyItemsByCodesParam.getApplyItemCodeList())) {
            return ChannelListResultUtil.error(MiddleResultEnum.FAILED.getCode(), "SunyurPurchaseApplyServiceImpl getPurchaserApplyItemsByItemCodes param is null");
        }
        // 查询参数按长度分割
        List<List<String>> applyItemCodesList = Lists.partition(purchaseApplyItemsByCodesParam.getApplyItemCodeList(), 50);
        // 返回结果集
        List<PurchaserApplyItemModel> purchaserItemsList = Lists.newArrayList();
        // 循环查询采购单行接口
        PurchaseApplyItemsByCodesParam itemCodes = new PurchaseApplyItemsByCodesParam();
        TypeReference<SunyurResult<List<PurchaserApplyItemModel>>> typeReference = new TypeReference<SunyurResult<List<PurchaserApplyItemModel>>>() {};
        for (List<String> strings : applyItemCodesList) {
            // 查询条件组装
            itemCodes.setApplyItemCodeList(strings);
            // 调用主线查询采购单行信息接口
            SunyurResult<List<PurchaserApplyItemModel>> sunyurResult = sunyurClient.execPost(getApplyItemsByCodes, JSON.toJSONString(itemCodes), typeReference);
            // 某次调用主线返回错误（小概率，可能网络等原因，此时结果集数据不完整，本次查询失败）
            if (!SunyurResultUtil.isSuccess(sunyurResult)) {
                LOGGER_ERROR.error("getPurchaserApplyItemsByItemCodes loop call sunyur request fail, param is {}, result is {}", JSON.toJSONString(itemCodes), JSON.toJSONString(sunyurResult));
                return ChannelListResultUtil.error(MiddleResultEnum.FAILED.getCode(), sunyurResult.getErrorMessage());
            }
            // 结果集组装
            purchaserItemsList.addAll(sunyurResult.getContent());
        }
        return ChannelListResultUtil.success(purchaserItemsList);
    }

    /**
     * @description 根据请购号 查询 采购单头信息
     * @param purchaseApplyHeadByCodeParam
     * @return com.sunyur.tailor.channel.common.middle.base.ChannelResult<java.util.List<com.sunyur.tailor.channel.service.inner.purchase.vo.PurchaserApplyHeadVO>>
     * @author yu.chen
     * @date 2021/4/23 22:14
     * @Version v1.0
     */
    @Override
    public ChannelResult<PurchaserApplyHeadModel> getPurchaserApplyHeadByCode(PurchaseApplyHeadByCodeParam purchaseApplyHeadByCodeParam){
        LOGGER_INFO.info("SunyurPurchaseApplyServiceImpl getPurchaserApplyHeadByCode param is {}", JSON.toJSONString(purchaseApplyHeadByCodeParam));
        if (ObjectUtils.isEmpty(purchaseApplyHeadByCodeParam) || StringUtils.isBlank(purchaseApplyHeadByCodeParam.getApplyCode())) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), "SunyurPurchaseApplyServiceImpl getPurchaserApplyHeadByCode param is null");
        }
        // 调用主线查询采购单头信息接口
        SunyurResult<PurchaserApplyHeadModel> sunyurResult = sunyurClient.execPost(getApplyHeadByCode, JSON.toJSONString(purchaseApplyHeadByCodeParam), new TypeReference<SunyurResult<PurchaserApplyHeadModel>>() {});
        // 主线返回错误
        if (!SunyurResultUtil.isSuccess(sunyurResult)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), sunyurResult.getErrorMessage());
        }
        return ChannelResultUtil.success(sunyurResult.getContent());
    }

    /**
     * @description 根据请购号 查询 采购单行集合
     * @param purchaseApplyItemsByCodeParam
     * @return com.sunyur.tailor.channel.common.middle.base.ChannelListResult<com.sunyur.tailor.channel.service.inner.purchase.model.PurchaserApplyItemModel>
     * @author yu.chen
     * @date 2021/4/28 22:14
     * @Version v1.0
     */
    @Override
    public ChannelListResult<PurchaserApplyItemModel> getPurchaserApplyItemsHeadByCode(PurchaseApplyItemsByCodeParam purchaseApplyItemsByCodeParam){
        LOGGER_INFO.info("SunyurPurchaseApplyServiceImpl getPurchaserApplyItemsHeadByCode param is {}", JSON.toJSONString(purchaseApplyItemsByCodeParam));
        if (ObjectUtils.isEmpty(purchaseApplyItemsByCodeParam) || StringUtils.isBlank(purchaseApplyItemsByCodeParam.getApplyCode())) {
            return ChannelListResultUtil.error(MiddleResultEnum.FAILED.getCode(), "SunyurPurchaseApplyServiceImpl getPurchaserApplyItemsHeadByCode param is null");
        }
        // 设置为每页最大条数
        purchaseApplyItemsByCodeParam.setPageSize(100);
        // 调用主线查询采购单头信息接口
        TypeReference<SunyurListResult<PurchaserApplyItemModel>> typeReference = new TypeReference<SunyurListResult<PurchaserApplyItemModel>>() {
        };
        SunyurListResult<PurchaserApplyItemModel> sunyurResult = sunyurClient.execListPost(getApplyItemsByCode, JSON.toJSONString(purchaseApplyItemsByCodeParam), typeReference);
        // 主线返回错误
        if (!SunyurResultUtil.isSuccess(sunyurResult)) {
            return ChannelListResultUtil.error(MiddleResultEnum.FAILED.getCode(), sunyurResult.getErrorMessage());
        }
        // 判断是否存在下一页
        if (!SunyurResultUtil.isNextPage(sunyurResult)) {
            return ChannelListResultUtil.success(sunyurResult.getContent());
        }

        // 返回结果集
        List<PurchaserApplyItemModel> purchaserApplyItemModelList = Lists.newArrayList();
        // 将第一次查询的结果收集
        purchaserApplyItemModelList.addAll(sunyurResult.getContent());
        // 循环查询剩余数据
        for (int i = purchaseApplyItemsByCodeParam.getPage() + 1; i <= sunyurResult.getTotalPage(); i++) {
            purchaseApplyItemsByCodeParam.setPage(i);
            // 调用主线查询采购单头信息接口
            SunyurListResult<PurchaserApplyItemModel> sunyurPageResult = sunyurClient.execListPost(getApplyItemsByCode, JSON.toJSONString(purchaseApplyItemsByCodeParam), typeReference);
            // 某次调用主线返回错误（小概率，可能网络等原因，此时结果集数据不完整，本次查询失败）
            if (!SunyurResultUtil.isSuccess(sunyurPageResult)) {
                LOGGER_ERROR.error("getPurchaserApplyItemsHeadByCode loop call sunyur request fail, param is {}, result is {}", JSON.toJSONString(purchaseApplyItemsByCodeParam), JSON.toJSONString(sunyurPageResult));
                return ChannelListResultUtil.error(MiddleResultEnum.FAILED.getCode(), sunyurPageResult.getErrorMessage());
            }
            purchaserApplyItemModelList.addAll(sunyurPageResult.getContent());
        }
        return ChannelListResultUtil.success(purchaserApplyItemModelList);
    }



    @Override
    public ChannelResult<List<ListPriceParityModel>> getListPriceParity(ListPriceParityParam getListPriceParityModel) throws Exception {
        LOGGER_INFO.info("SunyurCategoryServiceImpl getListPriceParity param is {}", JSON.toJSONString(getListPriceParityModel));
        if (ObjectUtils.isEmpty(getListPriceParityModel)) {
            return ChannelResultUtil.error(MiddleResultEnum.PARAM_NULL.getCode(), "SunyurCategoryServiceImpl getListPriceParity param is null");
        }
        List<ListPriceParityModel> resultList=new ArrayList<>();
        List<List<String>> materielList=Lists.partition(getListPriceParityModel.getApplyItemCodeList(),20);
        // 错误信息List
        List<String> errorMsgList = Lists.newArrayList();
        ListPriceParityParam listPriceParityParamClient = new ListPriceParityParam();
        TypeReference<SunyurResult<List<ListPriceParityModel>>> typeReference = new TypeReference<SunyurResult<List<ListPriceParityModel>>>() {
        };
        for (List<String> strings : materielList) {
            listPriceParityParamClient.setApplyItemCodeList(strings);
            // 调用主线接口
            SunyurResult<List<ListPriceParityModel>> sunyurResult = sunyurClient.execPost(getListPriceParity, JSON.toJSONString(listPriceParityParamClient), typeReference);
            if (sunyurResult.getCode().equals("00000")) {
                resultList.addAll(sunyurResult.getContent());
            } else {
                LOGGER_ERROR.error("getListPriceParity7 loop call sunyur request fail, param is {}, result is {}", JSON.toJSONString(listPriceParityParamClient), JSON.toJSONString(sunyurResult));
                // 每批次错误信息收集
                errorMsgList.add(sunyurResult.getContent() + "-" + sunyurResult.getErrorMessage());
            }
        }
        // 存在错误信息
        if (!CollectionUtils.isEmpty(errorMsgList)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), JSON.toJSONString(errorMsgList));
        }
        return ChannelResultUtil.success(resultList);
    }
}
